import React from 'react';
import clsx from 'clsx';
import { useSelector } from 'react-redux';
import { Formik, Form } from 'formik';
import { getUserSelector } from "../../../store/selectors/selectUserData";
import { FormikField } from '../../../components/FormikField/FormikField';
import { useConfirmationModal } from
    '../../../components/ConfirmationModalProvider/ConfirmationModalProvider';
import Flex from '../../../shared/ui/Flex/Flex';
import CardRow from '../../CardRow/CardRow';
import { StyledLabelCard } from '../LabelCard.styled';
import ContainerCard from '../../ContainerCard/ContainerCard';
import Textfield from '../../../shared/ui/Textfield/Textfield';
import Button from '../../../shared/ui/Button/Button';
import buttonStyles from '../ButtonStyle.module.scss';
import styles from './SecurityCard.module.scss';
import userServices from '../../../services/userServices';
import { validationChangePasswordSchema } from './SecurityCard.validation';

/**
 * @function SecurityCard - Отображает карточку смены пароля.
 * @returns { React.JSX.Element } - Компонент карточки для смены пароля.
 */
const SecurityCard: React.FC = (): React.JSX.Element => {

    /**
     * Ссылка на карточку смены пароля.
     */
    const securityCardRef = React.useRef<HTMLDivElement>(null);

    /**
     * Получение сохраненных в хранилище redux данных пользователя.
     */
    const userData = useSelector(getUserSelector);

    /**
     * Получение функций открытия/закрытия модального окна.
     */
    const { open, close } = useConfirmationModal();

    return (
        <div className={styles.securityCard} id="securityCard" ref={securityCardRef}>
            <StyledLabelCard>Безопасность</StyledLabelCard>
            <ContainerCard>
                <Formik
                    validationSchema={validationChangePasswordSchema}
                    initialValues={{
                        currentPassword: "",
                        newPassword: ""
                    }}
                    onSubmit={
                        async (values, { resetForm }) => {
                            try {
                                await userServices.changePassword({
                                    username: userData.username,
                                    currentPassword: values.currentPassword,
                                    newPassword: values.newPassword,
                                    confirmPassword: values.newPassword
                                });

                                open({
                                    content: "Пароль успешно сохранен",
                                    actions: (
                                        <Flex justifyContent="space-around">
                                            <Button onClick={close}>Ok</Button>
                                        </Flex>
                                    )
                                })
                                resetForm();

                            } catch (error) {
                                open({
                                    content: error?.response?.data?.message,
                                    actions: (
                                        <Flex justifyContent="space-around">
                                            <Button onClick={close}>Ok</Button>
                                        </Flex>
                                    )
                                })
                            }
                        }
                    }
                >
                    {({ handleSubmit }) => (
                        <Form
                            className={styles.securityForm}
                            onSubmit={(event) => {
                                event.preventDefault();
                                handleSubmit();
                            }}
                        >
                            <CardRow
                                className={styles.cardRow}
                                label="Текущий пароль"
                                action={
                                    <>
                                        <FormikField name="currentPassword">
                                            <Textfield type="password" />
                                        </FormikField>
                                        <div className={styles.fillerDiv}></div>
                                    </>
                                }
                            />
                            <CardRow
                                className={styles.cardRow}
                                label="Новый пароль"
                                action={
                                    <>
                                        <FormikField name="newPassword">
                                            <Textfield type="password" />
                                        </FormikField>
                                        <div className={styles.fillerDiv}></div>
                                    </>
                                }
                            />
                            <div className={clsx(styles.securityFlex, styles.securityButton)}>
                                <Button
                                    type="submit"
                                    className={buttonStyles.buttonStyle}
                                >
                                    Изменить
                                </Button>
                            </div>
                        </Form>
                    )}
                </Formik>
            </ContainerCard>
        </div>
    );
};

export default SecurityCard;